<template>
    <div>
        <a-modal :footer="null" :visible="visible" title="导入" @cancel="handleCancel">
            <a-form ref="importFormRef" :model="formdata" name="basic" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
                <a-form-item label="文件地址">
                    <a-row>
                        <a-col :span="18">
                            <a-form-item name="fileUrl">
                                <a-input disabled v-model:value="formdata.fileUrl" />
                            </a-form-item>
                        </a-col>
                        <a-col :span="6">
                            <a-upload :fileList="[]" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" :before-upload="beforeUpload">
                                <a-button style="margin-left: 20px" type="primary">选择文件</a-button>
                            </a-upload>
                        </a-col>
                    </a-row>
                </a-form-item>

                <template v-if="!!sheetTplInfo.length">
                    <a-form-item v-for="item in sheetTplInfo" :key="item.key" :label="`${item.name}模版`">
                        <a-row>
                            <a-col :span="18">
                                <a-form-item :name="item.key">
                                    <a-select
                                        v-model:value="formdata[item.key]"
                                        :filter-option="filterOption"
                                        show-search
                                        allowClear
                                        placeholder="请选择"
                                        :field-names="{ label: 'name', value: 'id' }"
                                        :options="item.options"
                                        @select="curSelect"
                                    ></a-select>
                                </a-form-item>
                            </a-col>
                            <a-col :span="6">
                                <a-button style="margin-left: 20px" type="primary" @click="selectTem(item.key)">更多模版</a-button>
                            </a-col>
                        </a-row>
                        <p v-if="tipsObj[item.key]">
                            根据选择的文件自动匹配导入模板，当前模板匹配度<span class="tipTitle">{{ tipsObj[item.key] }}%</span>
                        </p>
                    </a-form-item>
                </template>

                <!-- <a-form-item label="tip" name="" class="tipItem">
                    <p class="tipTitle">根据选择的文件自动匹配导入模板，当前模板匹配度{{ redMsg }}</p>
                </a-form-item> -->

                <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
                    <a-button type="primary" @click="handleCancel">取消</a-button>
                    <a-button :disabled="isDisable" style="margin-left: 30px" type="primary" @click="goToAddTpl">新增模版</a-button>
                    <a-button disabled="true" style="margin-left: 30px" type="primary" @click="preview">预览</a-button>
                    <a-button :disabled="isDisable" style="margin-left: 30px" type="primary" html-type="submit" @click="handleConfirm">确认</a-button>
                </a-form-item>
            </a-form>
        </a-modal>

        <a-modal destroyOnClose :zIndex="1024" v-model:visible="moreVisible" title="更多模版" okText="确认" cancelText="取消" @ok="confirmTem">
            <a-select
                style="width: 100%"
                v-model:value="currentTemValue"
                :filter-option="filterOption"
                show-search
                allowClear
                placeholder="请选择"
                :field-names="{ label: 'name', value: 'id' }"
                :options="allTplInfo"
                @select="handleSelect"
            ></a-select>
        </a-modal>
    </div>
</template>

<script>
import LuckyExcel from 'luckyexcel';

import { toSheetsTable } from '@/util/luckysheetToTable';
import { importData } from '@/request/api/dataSourceAPI';
import { message } from 'ant-design-vue';

export default {
    props: {
        visible: {
            type: Boolean,
            default: false,
        },
        sheetTplInfo: {
            type: Array,
            default: () => [],
        },
        allTplInfo: {
            type: Array,
            default: () => [],
        },
        tenRowData: {
            type: Array,
            default: () => [],
        },
        allRowData: {
            type: Array,
            default: () => [],
        },
    },
    data() {
        return {
            moreVisible: false, // 更多模版 modal 状态
            // 导入对话框红色提示文字
            redMsg: '_%',
            isDisable: true,
            formdata: {
                fileUrl: '',
            },
            // 选择文件时保存的文件
            uploadBtnFile: '',
            currentTemKey: '',
            currentTemValue: '', // 当前选择的模版值
            // 更多模板下拉框选中节点
            moreSelected: {},
            tipsObj: {},
        };
    },
    methods: {
        // 选择文件按钮 点击事件
        beforeUpload(file) {
            console.log(this.formdata);
            this.isDisable = false;
            this.formdata = {
                fileUrl: '',
            };
            this.tipsObj = {};
            this.uploadBtnFile = file;
            this.formdata.fileUrl = file.name;
            this.$emit('fileBeforeUpload', file);
            return false;
        },

        // 导入弹窗 模板下拉选中事件，拿取当前的tip
        curSelect(val, option) {
            this.tipsObj[option.key] = option.suitability;
        },

        // 更多模版按钮 点击事件
        selectTem(key) {
            this.moreVisible = true;
            this.currentTemKey = key;
        },

        // 更多模板弹窗 下拉选中事件
        handleSelect(value, option) {
            this.moreSelected = { ...option, key: this.currentTemKey };
        },

        // 更多模板弹窗 确认按钮事件
        confirmTem() {
            let currSheetTplOptions = this.sheetTplInfo[this.currentTemKey]['options'];
            let flag = currSheetTplOptions.every((item) => {
                return item.id != this.moreSelected.id;
            });
            if (flag) {
                this.sheetTplInfo[this.currentTemKey]['options'].push(this.moreSelected);
            }
            this.formdata[this.currentTemKey] = this.currentTemValue;
            this.tipsObj[this.currentTemKey] = this.moreSelected?.suitability;
            this.moreVisible = false;
            this.currentTemValue = '';
        },

        // 导入模板下拉输入检索
        filterOption(input, option) {
            return option.name.toLowerCase().indexOf(input.toLowerCase()) >= 0;
        },

        // 导入弹窗 确认按钮
        handleConfirm() {
            debugger;
            let data = {
                fullname: '',
                name: this.allRowData[0]['table']['fileName'],
                sheets: this.allRowData,
            };
            // 导入excel文件保存落库
            importData(data).then((res) => {
                if (res.state == '200') {
                    return message.success(res.msg || '导入成功！');
                } else {
                    return message.error(res.msg || '导入失败！');
                }
            });
            // let currInstance = this;
            // console.log(currInstance.formdata);
            // const file = this.uploadBtnFile;
            // LuckyExcel.transformExcelToLucky(file, (exportJson, luckysheetfile) => {
            //     if (exportJson.sheets == null || exportJson.sheets.length == 0) {
            //         alert('请选择.xlsx格式文件!');
            //         return;
            //     }
            //     // console.log(luckysheetfile,'luckysheetfile------------')
            //     luckysheet.destroy();
            //     luckysheet.create({
            //         container: 'luckysheet_for_trans_data',
            //         showinfobar: false, // 是否显示顶部信息栏
            //         data: exportJson.sheets,
            //         hook: {
            //             workbookCreateAfter: function () {
            //                 // currInstance.exportJson = _.cloneDeep(exportJson)
            //                 let data = {
            //                     fullname: '',
            //                     name: exportJson.info.name,
            //                     sheets: toSheetsTable(exportJson.sheets, exportJson.info.name, 1),
            //                 };
            //                 // 导入excel文件保存落库
            //                 importData(data).then((res) => {
            //                     if (res.state != 'SUCCESS') return message.error(res.msg)
            //                 });
            //             },
            //         },
            //     });
            // });
        },

        // 导入弹窗 取消按钮
        handleCancel() {
            this.isDisable = true;
            this.formdata = {};
            this.$refs.importFormRef.resetFields();
            this.$emit('changeVisible');
            this.$emit('newOpen');
        },

        // 导入弹窗 新增模板按钮
        goToAddTpl() {
            // 调用父组件方法，传入10行数据，请求模板详细信息
            this.$emit('addTpl');
            // 通过共同的父组件，展开抽屉页。方法写在共同的父组件中
            // this.$emit('changeIsvisible');
        },

        // 导入弹窗 预览按钮
        preview() {
            this.$emit('changeIsvisible');
        },
    },
};
</script>

<style lang="less" scoped>
.ant-form {
    margin-left: -130px;
}

.ant-form-item {
    margin-bottom: 15px;
}

.tipTitle {
    color: red;
}

.tipItem {
    :deep(.ant-form-item-label) {
        visibility: hidden;
    }
}
</style>
